<template>
  <div class="medical-order-tab">
    <!-- 医嘱列表 -->
    <van-list
      v-model:loading="loading"
      :finished="finished"
      finished-text="没有更多了"
      @load="onLoad"
    >
      <div class="order-list">
        <div 
          v-for="order in orderList" 
          :key="order.id" 
          class="order-item"
          @click="showOrderDetail(order)"
        >
          <div class="order-name">{{ order.orderName }}</div>
          <div class="order-info">
            <div class="order-time">开立时间: {{ formatDate(order.orderTime) }}</div>
            <div class="order-status">
              <van-tag :type="getStatusType(order.status)">{{ getStatusText(order.status) }}</van-tag>
            </div>
          </div>
          <van-icon name="arrow" class="arrow-icon" />
        </div>
        
        <div v-if="orderList.length === 0 && !loading" class="empty-tip">
          <template v-if="hasError">
            <div class="error-text">加载失败</div>
            <van-button type="primary" size="small" @click="retryLoad">重试</van-button>
          </template>
          <template v-else>
            暂无{{ tabName }}数据
          </template>
        </div>
      </div>
    </van-list>
    
    <!-- 医嘱详情弹出层 -->
    <van-popup
      v-model:show="showDetail"
      position="bottom"
      class="detail-popup"
      overlay
      teleport="body"
      round
      closeable
    >
      <div class="detail-container">
        <div class="detail-header">{{ tabName }}详情</div>
        
        <div class="detail-content" v-if="currentOrder">
          <div class="order-detail-title">{{ currentOrder.orderName }}</div>
          
          <van-cell-group inset class="info-group">
            <van-cell title="项目名称" :value="currentOrder.orderName" />
            <van-cell title="项目编码" :value="currentOrder.orderCode" />
            <van-cell title="医嘱号" :value="currentOrder.orderNo" />
            <template v-if="orderType === 1">
              <van-cell title="规格" :value="currentOrder.specification || '无'" />
              <van-cell title="用量" :value="currentOrder.dosage || '无'" />
              <van-cell title="用法" :value="currentOrder.usages || '无'" />
              <van-cell title="频次" :value="currentOrder.frequency || '无'" />
              <van-cell title="数量" :value="currentOrder.quantity" />
            </template>

            <van-cell title="开立时间" :value="formatDate(currentOrder.orderTime)" />
            <van-cell title="开立医生" :value="currentOrder.orderDoctorName || '未知'" />
            <van-cell title="执行时间" :value="formatDate(currentOrder.executeTime) || '未执行'" />
            <!-- <van-cell title="执行护士" :value="currentOrder.executeNurseName || '未执行'" /> -->
            <van-cell title="完成时间" :value="formatDate(currentOrder.completeTime) || '未完成'" />
            <van-cell title="状态" :value="getStatusText(currentOrder.status)" />
            <van-cell title="备注" :value="currentOrder.remark || '无'" />
          </van-cell-group>
          
          <!-- 检查报告展示 -->
          <template v-if="(orderType === 2|| orderType === 3) && currentReport">
            <van-cell-group inset title="检查报告" class="report-section">
              <!-- <van-cell title="报告号" :value="currentReport.reportNo" /> -->
              <van-cell title="报告时间" :value="formatDate(currentReport.reportTime)" />
              <van-cell title="报告医生" :value="currentReport.reporterName || '未知'" />
              <van-cell title="审核医生" :value="currentReport.reviewerName || '未知'" />
            </van-cell-group>
            
            <van-cell-group inset title="报告内容" class="report-section">
              <div class="report-content">{{ currentReport.reportContent || '暂无报告内容' }}</div>
            </van-cell-group>
            
            <van-cell-group inset title="报告图片" class="report-section" v-if="currentReport.imageUrls">
              <div class="report-images">
                <van-image
                  v-for="(url, index) in parseImageUrls(currentReport.imageUrls)"
                  :key="index"
                  :src="url"
                  width="100"
                  height="100"
                  fit="cover"
                  radius="4px"
                  @click="showImagePreview(parseImageUrls(currentReport.imageUrls), index)"
                />
              </div>
            </van-cell-group>
          </template>
          
          <!-- 检验报告展示 -->
          <!-- <template v-if="(orderType === 3 || orderType === 4) && currentReport">
            <van-cell-group inset title="检验报告" class="report-section">
              <van-cell title="报告号" :value="currentReport.reportNo" />
              <van-cell title="报告时间" :value="formatDate(currentReport.reportTime)" />
              <van-cell title="报告医生" :value="currentReport.reporterName || '未知'" />
              <van-cell title="审核医生" :value="currentReport.reviewerName || '未知'" />
            </van-cell-group>
            
            <van-cell-group inset title="报告内容" class="report-section">
              <div class="report-content">{{ currentReport.reportContent || '暂无报告内容' }}</div>
            </van-cell-group>
          </template> -->
        </div>
      </div>
    </van-popup>
  </div>
</template>

<script setup>
import { ref, onMounted, watch } from 'vue';
import { showToast, showImagePreview } from 'vant';
import { getMedicalOrderList, getMedicalOrderDetail } from '@/api/patient';
import { requestWithRetry } from '@/utils/request';

const props = defineProps({
  visitId: {
    type: [String, Number],
    required: true
  },
  orderType: {
    type: [String, Number],
    required: true
  },
  tabName: {
    type: String,
    required: true
  }
});

// 医嘱列表数据
const orderList = ref([]);
const loading = ref(false);
const finished = ref(false);
const showDetail = ref(false);
const currentOrder = ref(null);
const currentReport = ref(null);
const hasError = ref(false);

// 获取医嘱列表
const fetchOrders = async () => {
  if (hasError.value) {
    finished.value = true;
    return;
  }

  try {
    loading.value = true;
    
    const data = {
      visitId: props.visitId,
      orderType: props.orderType
    };
    
    // 使用带重试机制的请求
    const res = await requestWithRetry({
      url: '/medicalOrder/list',
      method: 'post',
      data
    }, 2); // 最多重试2次
    
    if (res.data && res.data.length) {
      // 过滤当前类型的医嘱
      const filteredOrders = res.data.filter(order => order.orderType == props.orderType);
      orderList.value = [...filteredOrders];
    }
    
    // 加载完毕
    finished.value = true;
    hasError.value = false;
  } catch (error) {
    console.error('获取医嘱列表失败', error);
    showToast('获取医嘱列表失败');
    finished.value = true; // 确保出错时也设置完成状态
    hasError.value = true;
  } finally {
    loading.value = false;
  }
};

// 上拉加载
const onLoad = () => {
  if (!loading.value && !finished.value) {
    fetchOrders();
  } else {
    // 如果正在加载或已完成，直接标记加载完成
    finished.value = true;
  }
};

// 格式化日期
const formatDate = (dateStr) => {
  if (!dateStr) return '';
  
  try {
    const date = new Date(dateStr);
    return `${date.getFullYear()}-${String(date.getMonth() + 1).padStart(2, '0')}-${String(date.getDate()).padStart(2, '0')} ${String(date.getHours()).padStart(2, '0')}:${String(date.getMinutes()).padStart(2, '0')}`;
  } catch (e) {
    return dateStr;
  }
};

// 获取状态标签类型
const getStatusType = (status) => {
  const statusMap = {
    0: 'default',
    1: 'primary',
    2: 'success',
    3: 'warning',
    4: 'danger'
  };
  return statusMap[status] || 'default';
};

// 获取状态文本
const getStatusText = (status) => {
  const statusMap = {
    0: '未开始',
    1: '已开立',
    2: '已执行',
    3: '已完成',
    4: '已取消'
  };
  return statusMap[status] || '未知状态';
};

// 显示医嘱详情
const showOrderDetail = async (order) => {
  try {
    currentOrder.value = order;
    
    // 获取医嘱详情
    if (order.id) {
      const res = await requestWithRetry({
        url: '/medicalOrder/selectMedicalOrderById',
        method: 'get',
        params: { id: order.id }
      });
      
      if (res.data) {
        currentOrder.value = res.data;
      }
    }
    
    // 如果有报告，获取报告信息（假设有报告接口）
    if (props.orderType === 2 || props.orderType === 3) {
      // 检查报告和检验报告会有相应的报告信息
      // TODO: 实际应该调用获取报告的接口
      // 这里暂时模拟一个报告数据
      currentReport.value = {
        reportNo: `${order.orderNo}-R`,
        reportTime: order.orderTime,
        reporterName: '报告医生',
        reviewerName: '审核医生',
        reportContent: '报告内容示例，这里应该显示真实的报告内容。',
        imageUrls: 'https://img01.yzcdn.cn/vant/cat.jpeg,https://img01.yzcdn.cn/vant/dog.jpeg'
      };
    } else {
      currentReport.value = null;
    }
    
    // 显示详情弹出层
    showDetail.value = true;
  } catch (error) {
    console.error('获取医嘱详情失败', error);
    showToast('获取医嘱详情失败');
  }
};

// 重试加载
const retryLoad = () => {
  if (hasError.value) {
    hasError.value = false;
    finished.value = false;
    orderList.value = [];
    fetchOrders();
  }
};

// 解析图片URL
const parseImageUrls = (imageUrlsStr) => {
  if (!imageUrlsStr) return [];
  
  try {
    return imageUrlsStr.split(',').filter(url => url.trim() !== '');
  } catch (e) {
    return [];
  }
};

// 监听visitId变化，重新获取数据
watch(() => props.visitId, (newVal) => {
  if (newVal) {
    orderList.value = [];
    finished.value = false;
    hasError.value = false;
    fetchOrders();
  }
});

// 监听orderType变化，重新获取数据
watch(() => props.orderType, (newVal) => {
  if (newVal) {
    orderList.value = [];
    finished.value = false;
    hasError.value = false;
    fetchOrders();
  }
});

// 组件挂载后获取数据
onMounted(() => {
  fetchOrders();
});
</script>

<style scoped>
.medical-order-tab {
  padding: 0 0 20px 0;
}

.order-list {
  padding: 8px;
}

.order-item {
  background-color: #fff;
  margin-bottom: 8px;
  padding: 12px;
  border-radius: 8px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.05);
  position: relative;
}

.order-name {
  font-size: 16px;
  font-weight: bold;
  margin-bottom: 8px;
}

.order-info {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.order-time {
  font-size: 14px;
  color: #666;
}

.arrow-icon {
  position: absolute;
  right: 12px;
  top: 50%;
  transform: translateY(-50%);
  color: #999;
}

.empty-tip {
  text-align: center;
  color: #999;
  padding: 20px 0;
}

.error-text {
  color: #ee0a24;
  margin-bottom: 8px;
}

.detail-popup {
  height: 80%;
  max-height: 90vh;
}

.detail-container {
  height: 100%;
  display: flex;
  flex-direction: column;
  padding: 16px 16px 24px;
}

.detail-header {
  font-size: 18px;
  font-weight: bold;
  text-align: center;
  margin-bottom: 16px;
  padding-top: 8px;
}

.detail-content {
  flex: 1;
  overflow-y: auto;
  -webkit-overflow-scrolling: touch;
  padding-bottom: 16px;
}

.order-detail-title {
  font-size: 18px;
  font-weight: bold;
  margin-bottom: 16px;
  text-align: center;
  color: var(--primary-color, #1989fa);
}

.info-group {
  margin-bottom: 16px;
}

.report-section {
  margin-top: 16px;
}

.report-content {
  padding: 16px;
  color: #333;
  line-height: 1.8;
  white-space: pre-wrap;
  font-size: 15px;
  background-color: #f9f9f9;
  border-radius: 8px;
  min-height: 80px;
}

.report-images {
  padding: 16px;
  display: flex;
  flex-wrap: wrap;
  gap: 12px;
  justify-content: flex-start;
}
</style> 